// src/renderer/src/utils/database.js
class DatabaseClient {
  constructor() {
    // 不在构造函数中缓存sessionId，而是每次动态获取
  }

  // 获取当前有效的sessionId
  getSessionId() {
    const sessionId = localStorage.getItem('sessionId');
    if (!sessionId) {
      throw new Error('未找到会话ID，请重新登录');
    }
    return sessionId;
  }

  // 验证会话
  async verifySession() {
    const sessionId = this.getSessionId();

    const result = await window.electronAPI.invoke('auth-verify-session', {
      sessionId
    });
    
    if (!result.success || !result.isAuthenticated) {
      // 会话无效，清除本地存储
      localStorage.removeItem('sessionId');
      localStorage.removeItem('isAuthenticated');
      console.log(result);
      throw new Error(result.reason || '会话验证失败');
    }
    
    return true;
  }

  // 查询数据
  async query(sql, params = []) {
    await this.verifySession();
    
    const result = await window.electronAPI.invoke('db-query', {
      sessionId: this.getSessionId(),
      sql,
      params
    });
    
    if (!result.success) {
      throw new Error(result.error);
    }
    
    return result.data;
  }

  // 插入数据
  async insert(sql, params = []) {
    await this.verifySession();
    
    const result = await window.electronAPI.invoke('db-insert', {
      sessionId: this.getSessionId(),
      sql,
      params
    });
    
    if (!result.success) {
      throw new Error(result.error);
    }
    
    return result.id;
  }

  // 更新数据
  async update(sql, params = []) {
    await this.verifySession();
    
    const result = await window.electronAPI.invoke('db-update', {
      sessionId: this.getSessionId(),
      sql,
      params
    });
    
    if (!result.success) {
      throw new Error(result.error);
    }
    
    return result.changes;
  }

  // 删除数据
  async delete(sql, params = []) {
    await this.verifySession();
    
    const result = await window.electronAPI.invoke('db-delete', {
      sessionId: this.getSessionId(),
      sql,
      params
    });
    
    if (!result.success) {
      throw new Error(result.error);
    }
    
    return result.changes;
  }

  // 分页查询
  async paginate(table, page = 1, pageSize = 10, where = '', params = [], orderBy = 'id DESC') {
    await this.verifySession();
    
    const offset = (page - 1) * pageSize;
    const whereClause = where ? `WHERE ${where}` : '';
    
    const data = await this.query(
      `SELECT * FROM ${table} ${whereClause} ORDER BY ${orderBy} LIMIT ? OFFSET ?`,
      [...params, pageSize, offset]
    );
    
    const totalResult = await this.query(
      `SELECT COUNT(*) as total FROM ${table} ${whereClause}`,
      params
    );
    
    return {
      data,
      pagination: {
        page,
        pageSize,
        total: totalResult[0].total,
        totalPages: Math.ceil(totalResult[0].total / pageSize)
      }
    };
  }

async batchInsert(sql, values = []) {
  await this.verifySession();
  
  // 额外校验：确保 values 是二维数组（避免前端传错）
  if (!Array.isArray(values) || values.some(item => !Array.isArray(item))) {
    throw new Error('批量插入参数错误：values 必须是二维数组');
  }
  
  const result = await window.electronAPI.invoke('db-batch-insert', {
    sessionId: this.getSessionId(),
    sql,
    values // 确保这里传递的是二维数组
  });
  
  if (!result.success) {
    throw new Error(result.error);
  }
  
  return result.count;
}

}

export default new DatabaseClient();